package com.xjaq.dify.interceptor;

import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor;
import com.xjaq.dify.config.DiFyConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@Slf4j
public class DifyInterceptor extends BasePathMatchInterceptor {
    @Autowired
    private DiFyConfig diFyConfig;
    @Override
    protected Response doIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request build = request.newBuilder()
                .addHeader("Authorization", "Bearer " + diFyConfig.getApiKey())
                .addHeader("Content-Type", "application/json")
                .addHeader("Host" , diFyConfig.getHost())
//                .addHeader("Accept", "text/event-stream")
                .build();
        log.info("请求头: " + build.headers());
//        log.info("请求体: " + build.body());
        // 如果有请求体，记录请求体内容
        if (request.body() != null) {
            // 缓冲请求体以便可以多次读取
            Request copy = request.newBuilder().build();
            Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            String requestBody = buffer.readUtf8();
            log.info("请求体内容: " + requestBody);
        }
        return chain.proceed(build);
    }
}
